<?php

defined( 'PDNS_CORE' ) or die( "Unauthorized" );

class DB{
	/*
		standard singleton pattern
	*/
	private static $instance;

	// query log for debug
	private $query_log = array();
	
	public static function getInstance(){
		if (!isset(self::$instance)) {
			$c = __CLASS__;
			self::$instance = new $c();
		}
		return self::$instance;
	}

	/**
	 *  @return array of queries executed
	 */
	public static function getQueryLog(){
		$db = self::getInstance();
		return $db->query_log;
	}

	function __construct(){
		$config = Config::getInstance();
		$user = User::getInstance();

		$this->host = $config->db_host;
		$this->user = $user->name;
		$this->pass = $user->pass;
		$this->db = $config->db_db;
		$this->prefix = $config->db_prefix;
		
		$this->link = @mysql_connect( $this->host, $this->user, $this->pass );

		if( ! $this->link )
			throw new Exception( "Can not connect to MySQL" );
		
		if( ! @mysql_select_db( $this->db, $this->link ))
			throw new Exception( mysql_error() );
	}

	public function query( $query ){
		if( Config::get('debug') )
			$this->query_log[] = $query;

		$result = mysql_query($query);
		
		if (!$result) {
			throw new Exception( 'Query failed: ' . mysql_error() );
		}

		return $result;
	}

	/**
	 *  queries man sql statements seperated by ;
	 *  @param string $sql the sql statements
	 */
	public function manyQuery( $sql ){
		// remove newlines
		$sql = str_replace( "\n", '', $sql );
		// seperate into seperate statements
		$sql = explode( ';', $sql );

		foreach( $sql as $query ){
			$this->query( $query );
		}
	}

	/**
	 *  executes the sql in $file 
	 *  @param string $file file to obtain sql from
	 */
	public function import( $file ){
		$contents = file_get_contents( $file );

		if ( $contents===false ) {
			throw new Exception( "Could not open sql file $file" );
		}
		$this->manyQuery( $contents );
	}

	public function fetch_objects( $query, $index='' ){
		$result = $this->query( $query );

		$objects = array();
		while( $row = mysql_fetch_object($result) ){
			if( !$index )
				$objects[] = $row;
			else{
				if ( !isset( $row->$index )) {
					throw new Exception( "Index does not exist: $index Query: $query" );
				}
				$objects[$row->$index] = $row;
			}
		}
		mysql_free_result($result);

		return $objects;
	}
	
	public function fetch_object( $query ){
		$result = $this->query( $query );

		return mysql_fetch_object($result);
	}

	public function delete( $what, $col, $table ){
		$query = "DELETE FROM $table WHERE $col='$what'";
		
		$this->query( $query );
		
		return mysql_affected_rows();
	}

	/**
	 *  Appends to log in database
	 *
	 */
	public function log( $type, $domain, $msg ){
		$user = User::getInstance();
		$query = "INSERT INTO {$this->prefix}log (user, type, domain, msg) VALUES ('{$user->name}', '$type', '$domain', '$msg')";
		$result = $this->query( $query );
	}
}
